"""
简化的日志系统，避免循环依赖
"""

import logging
import logging.handlers
from pathlib import Path
from datetime import datetime


class SimpleLogger:
    """简化的日志管理器，避免复杂的依赖"""
    
    _loggers = {}
    _initialized = False
    _log_dir = None
    
    @classmethod
    def init(cls, base_dir: Path):
        """初始化日志系统"""
        if cls._initialized:
            return
            
        cls._log_dir = base_dir / "logs"
        cls._log_dir.mkdir(parents=True, exist_ok=True)
        
        # 创建子目录
        for subdir in ["app", "hardware", "web", "errors"]:
            (cls._log_dir / subdir).mkdir(exist_ok=True)
        
        # 配置根日志记录器
        root = logging.getLogger()
        root.setLevel(logging.DEBUG)
        
        # 清理现有处理器
        for handler in root.handlers[:]:
            root.removeHandler(handler)
            
        # 配置Werkzeug日志(减少噪音)
        logging.getLogger('werkzeug').setLevel(logging.WARNING)
        
        cls._initialized = True
    
    @classmethod
    def get_logger(cls, name: str, log_type: str = "app", level: str = "INFO") -> logging.Logger:
        """获取日志记录器"""
        if not cls._initialized:
            # 如果未初始化，尝试自动初始化或返回基本logger
            try:
                from .config import BASE_DIR
                cls.init(BASE_DIR)
            except:
                # 如果自动初始化失败，返回基本logger，但不输出到控制台
                basic_logger = logging.getLogger(name)
                basic_logger.addHandler(logging.NullHandler())
                return basic_logger
            
        logger_key = f"{log_type}.{name}"
        
        if logger_key in cls._loggers:
            return cls._loggers[logger_key]
            
        logger = logging.getLogger(logger_key)
        logger.setLevel(getattr(logging, level.upper()))
        
        # 避免重复添加处理器
        if logger.handlers:
            return logger
            
        # 文件处理器
        log_file = cls._log_dir / log_type / f"{name}.log"
        file_handler = logging.handlers.RotatingFileHandler(
            log_file,
            maxBytes=10*1024*1024,  # 10MB
            backupCount=5,
            encoding='utf-8'
        )
        
        # 文件格式 - 详细
        file_formatter = logging.Formatter(
            '%(asctime)s | %(levelname)-8s | %(name)s | %(message)s',
            datefmt='%Y-%m-%d %H:%M:%S'
        )
        file_handler.setFormatter(file_formatter)
        
        # 控制台处理器 - 简洁 
        console_handler = logging.StreamHandler()
        
        # 硬件日志在控制台显示WARNING级别以上，减少串口错误刷屏
        if log_type == "hardware":
            console_handler.setLevel(logging.ERROR)
            file_handler.setLevel(logging.WARNING)
        else:
            console_handler.setLevel(logging.INFO)
            file_handler.setLevel(logging.DEBUG)
            
        console_formatter = logging.Formatter(
            '%(asctime)s | %(levelname)s | %(name)s | %(message)s',
            datefmt='%H:%M:%S'
        )
        console_handler.setFormatter(console_formatter)
        
        logger.addHandler(file_handler)
        logger.addHandler(console_handler)
        logger.propagate = False
        
        cls._loggers[logger_key] = logger
        return logger


# 便捷函数
def get_logger(name: str, log_type: str = "app") -> logging.Logger:
    """获取日志记录器"""
    return SimpleLogger.get_logger(name, log_type)


def get_hardware_logger(device_name: str) -> logging.Logger:
    """获取硬件日志记录器，减少串口错误刷屏"""
    return SimpleLogger.get_logger(device_name, "hardware", "WARNING")


def get_app_logger(module_name: str) -> logging.Logger:
    """获取应用日志记录器"""
    return SimpleLogger.get_logger(module_name, "app", "INFO")


def get_web_logger() -> logging.Logger:
    """获取Web日志记录器"""
    return SimpleLogger.get_logger("flask", "web", "INFO")
